从 SpringMvc 源码分析其工作原理

您所在的位置:网站首页 spring mvc源码解析 从 SpringMvc 源码分析其工作原理

从 SpringMvc 源码分析其工作原理

2022-05-12 17:29| 来源: 网络整理| 查看: 265

1. MVC使用

在研究源码之前,先来回顾以下springmvc 是如何配置的,这将能使我们更容易了解源码。

1.1 web.xml mvc-dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring/spring-*.xml mvc-dispatcher /

值的注意的是contextConfigLocation和DispatcherServlet(用此类来阻拦请求)的引用和配置。

1.2 spring-web.xml

值的注意的是InternalResourceViewResolver,它会在ModelAndView返回的试图名前面加上prefix前缀,在后面加载suffix指定后缀。

SpringMvc主支源码分析

引用《Spring in Action》中的一张图来更好的理解执行过程:

上图流程总体来说可分为三大块:

Map的建立(并放入WebApplicationContext)HttpRequest请求中Url的请求阻拦解决(DispatchServlet解决)反射调用Controller中对应的解决方法,并返回视图

本文将围绕这三块进行分析。

1. Map的建立

在容器初始化时会建立所有 url 和 Controller 的对应关系,保存到 Map中,那是如何保存的呢。

ApplicationObjectSupport #setApplicationContext方法// 初始化ApplicationContext@Overridepublic void initApplicationContext() throws ApplicationContextException { super.initApplicationContext(); detectHandlers();}AbstractDetectingUrlHandlerMapping #detectHandlers()方法:/** * 建立当前ApplicationContext 中的 所有Controller 和url 的对应关系 * Register all handlers found in the current ApplicationContext. *

The actual URL determination for a handler is up to the concrete * {@link #determineUrlsForHandler(String)} implementation. A bean for * which no such URLs could be determined is simply not considered a handler. * @throws org.springframework.beans.BeansException if the handler couldn't be registered * @see #determineUrlsForHandler(String) */protected void detectHandlers() throws BeansException { if (logger.isDebugEnabled()) { logger.debug("Looking for URL mappings in application context: " + getApplicationContext()); } // 获取容器中的beanNames String[] beanNames = (this.detectHandlersInAncestorContexts ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) : getApplicationContext().getBeanNamesForType(Object.class)); // 遍历 beanNames 并找到对应的 url // Take any bean name that we can determine URLs for. for (String beanName : beanNames) { // 获取bean上的url(class上的url + method 上的 url) String[] urls = determineUrlsForHandler(beanName); if (!ObjectUtils.isEmpty(urls)) { // URL paths found: Let's consider it a handler. // 保存url 和 beanName 的对应关系 registerHandler(urls, beanName); } else { if (logger.isDebugEnabled()) { logger.debug("Rejected bean name '" + beanName + "': no URL paths identified"); } } }}determineUrlsForHandler()方法:

该方法在不同的子类有不同的实现,我这里分析的是DefaultAnnotationHandlerMapping类的实现,该类主要负责解决@RequestMapping注解形式的公告。

/** * 获取@RequestMaping注解中的url * Checks for presence of the {@link org.springframework.web.bind.annotation.RequestMapping} * annotation on the handler class and on any of its methods. */@Overrideprotected String[] determineUrlsForHandler(String beanName) { ApplicationContext context = getApplicationContext(); Class handlerType = context.getType(beanName); // 获取beanName 上的requestMapping RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class); if (mapping != null) { // 类上面有@RequestMapping 注解 this.cachedMappings.put(handlerType, mapping); Set urls = new LinkedHashSet(); // mapping.value()就是获取@RequestMapping注解的value值 String[] typeLevelPatterns = mapping.value(); if (typeLevelPatterns.length > 0) { // 获取Controller 方法上的@RequestMapping String[] methodLevelPatterns = determineUrlsForHandlerMethods(handlerType); for (String typeLevelPattern : typeLevelPatterns) { if (!typeLevelPattern.startsWith("/")) { typeLevelPattern = "/" + typeLevelPattern; } for (String methodLevelPattern : methodLevelPatterns) { // controller的映射url+方法映射的url String combinedPattern = getPathMatcher().combine(typeLevelPattern, methodLevelPattern); // 保存到set集合中 addUrlsForPath(urls, combinedPattern); } addUrlsForPath(urls, typeLevelPattern); } // 以数组形式返回controller上的所有url return StringUtils.toStringArray(urls); } else { // controller上的@RequestMapping映射url为空串,直接找方法的映射url return determineUrlsForHandlerMethods(handlerType); } } // controller上没@RequestMapping注解 else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) { // 获取controller中方法上的映射url return determineUrlsForHandlerMethods(handlerType); } else { return null; }}

更深的细节代码就比较简单了,有兴趣的可以继续深入。

到这里,Controller和Url的映射就装配完成,下来就分析请求的解决过程。

2. url的请求解决

我们在xml中配置了DispatcherServlet为调度器,所以我们就来看它的代码,可以从名字上看出它是个Servlet,那么它的核心方法就是doService()

DispatcherServlet #doService():/** * 将DispatcherServlet特定的请求属性和委托 公开给{@link #doDispatch}以进行实际调度。 * Exposes the DispatcherServlet-specific request attributes and delegates to {@link #doDispatch} * for the actual dispatching. */@Overrideprotected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isDebugEnabled()) { String requestUri = new UrlPathHelper().getRequestUri(request); logger.debug("DispatcherServlet with name '" + getServletName() + "' processing " + request.getMethod() + " request for [" + requestUri + "]"); } //在包含request的情况下保留请求属性的快照, //能够在include之后恢还原始属性。 Map attributesSnapshot = null; if (WebUtils.isIncludeRequest(request)) { logger.debug("Taking snapshot of request attributes before include"); attributesSnapshot = new HashMap(); Enumeration attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) { attributesSnapshot.put(attrName, request.getAttribute(attrName)); } } } // 使得request对象能供 handler解决和view解决 使用 request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext()); request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver); request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver); request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource()); try { doDispatch(request, response); } finally { // 假如不为空,则复原原始属性快照。 if (attributesSnapshot != null) { restoreAttributesAfterInclude(request, attributesSnapshot); } }}

可以看到,它将请求拿到后,主要是给request设置了少量对象,以便于后续工作的解决(Handler解决和view解决)。比方WebApplicationContext,它里面就包含了我们在第一步完成的controller与url映射的信息。

DispatchServlet # doDispatch()/** * 控制请求转发 * Process the actual dispatching to the handler. *

The handler will be obtained by applying the servlet's HandlerMappings in order. * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters * to find the first that supports the handler class. *

All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers * themselves to decide which methods are acceptable. * @param request current HTTP request * @param response current HTTP response * @throws Exception in case of any kind of processing failure */protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; try { ModelAndView mv; boolean errorView = false; try { // 1\. 检查能否是上传文件 processedRequest = checkMultipart(request); // Determine handler for the current request. // 2\. 获取handler解决器,返回的mappedHandler封装了handlers和interceptors mappedHandler = getHandler(processedRequest, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { // 返回404 noHandlerFound(processedRequest, response); return; } // Apply preHandle methods of registered interceptors. // 获取HandlerInterceptor的预解决方法 HandlerInterceptor[] interceptors = mappedHandler.getInterceptors(); if (interceptors != null) { for (int i = 0; i < interceptors.length; i++) { HandlerInterceptor interceptor = interceptors[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i; } } // Actually invoke the handler. // 3\. 获取handler适配器 Adapter HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // 4\. 实际的解决器解决并返回 ModelAndView 对象 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // Do we need view name translation? if (mv != null && !mv.hasView()) { mv.setViewName(getDefaultViewName(request)); } // HandlerInterceptor 后解决 if (interceptors != null) { for (int i = interceptors.length - 1; i >= 0; i--) { HandlerInterceptor interceptor = interceptors[i]; // 结束视图对象解决 interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } } catch (ModelAndViewDefiningException ex) { logger.debug("ModelAndViewDefiningException encountered", ex); mv = ex.getModelAndView(); } catch (Exception ex) { Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(processedRequest, response, handler, ex); errorView = (mv != null); } // Did the handler return a view to render? if (mv != null && !mv.wasCleared()) { render(mv, processedRequest, response); if (errorView) { WebUtils.clearErrorRequestAttributes(request); } } else { if (logger.isDebugEnabled()) { logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling"); } } // Trigger after-completion for successful outcome. // 请求成功响应之后的方法 triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); } catch (Exception ex) { // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } catch (Error err) { ServletException ex = new NestedServletException("Handler processing failed", err); // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } finally { // Clean up any resources used by a multipart request. if (processedRequest != request) { cleanupMultipart(processedRequest); } }}

该方法主要是

通过request对象获取到HandlerExecutionChain,HandlerExecutionChain对象里面包含了阻拦器interceptor和解决器handler。假如获取到的对象是空,则交给noHandlerFound返回404页面。阻拦器预解决,假如执行成功则进行3获取handler适配器 Adapter实际的解决器解决并返回 ModelAndView 对象

下面是该方法中的少量核心细节:

DispatchServlet #doDispatch # noHandlerFound核心源码:

response.sendError(HttpServletResponse.SC_NOT_FOUND);

DispatchServlet #doDispatch #getHandler方法事实上调用的是AbstractHandlerMapping #getHandler方法,我贴出一个核心的代码:

// 拿四处理对象Object handler = getHandlerInternal(request);...String handlerName = (String) handler;handler = getApplicationContext().getBean(handlerName);...// 返回HandlerExecutionChain对象return getHandlerExecutionChain(handler, request);

可以看到,它先从request里获取handler对象,这就证实了之前DispatchServlet #doService为什么要吧WebApplicationContext放入request请求对象中。

最终返回一个HandlerExecutionChain对象.

3. 反射调用解决请求的方法,返回结果视图

在上面的源码中,实际的解决器解决并返回 ModelAndView 对象调用的是mv = ha.handle(processedRequest, response, mappedHandler.getHandler());这个方法。该方法由AnnotationMethodHandlerAdapter #handle() #invokeHandlerMethod()方法实现.

AnnotationMethodHandlerAdapter #handle() #invokeHandlerMethod()/** * 获取解决请求的方法,执行并返回结果视图 */protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 1.获取方法解析器 ServletHandlerMethodResolver methodResolver = getMethodResolver(handler); // 2.解析request中的url,获取解决request的方法 Method handlerMethod = methodResolver.resolveHandlerMethod(request); // 3\. 方法调用器 ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver); ServletWebRequest webRequest = new ServletWebRequest(request, response); ExtendedModelMap implicitModel = new BindingAwareModelMap(); // 4.执行方法(获取方法的参数) Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel); // 5\. 封装成mv视图 ModelAndView mav = methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest); methodInvoker.updateModelAttributes(handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest); return mav;}

这个方法有两个重要的地方,分别是resolveHandlerMethod和invokeHandlerMethod。

resolveHandlerMethod 方法

methodResolver.resolveHandlerMethod(request):获取controller类和方法上的@requestMapping value,与request的url进行匹配,找四处理request的controller中的方法.最终拼接的具体实现是org.springframework.util.AntPathMatcher#combine方法。

invokeHandlerMethod方法

从名字就能看出来它是基于反射,那它做了什么呢。

解析该方法上的参数,并调用该方法。

//上面全都是为解析方法上的参数做准备...// 解析该方法上的参数Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);// 真正执行解析调用的方法return doInvokeMethod(handlerMethodToInvoke, handler, args);invokeHandlerMethod方法#resolveHandlerArguments方法

代码有点长,我就简介下它做了什么事情吧。

假如这个方法的参数用的是注解,则解析注解拿到参数名,而后拿到request中的参数名,两者一致则进行赋值(详细代码在HandlerMethodInvoker#resolveRequestParam),而后将封装好的对象放到args[]的数组中并返回。假如这个方法的参数用的不是注解,则需要asm框架(底层是读取字节码)来帮助获取到参数名,而后拿到request中的参数名,两者一致则进行赋值,而后将封装好的对象放到args[]的数组中并返回。invokeHandlerMethod方法#doInvokeMethod方法private Object doInvokeMethod(Method method, Object target, Object[] args) throws Exception { // 将一个方法设置为可调用,主要针对private方法 ReflectionUtils.makeAccessible(method); try { // 反射调用 return method.invoke(target, args); } catch (InvocationTargetException ex) { ReflectionUtils.rethrowException(ex.getTargetException()); } throw new IllegalStateException("Should never get here");}

到这里,即可以对request请求中url对应的controller的某个对应方法进行调用了。

总结:

看完后脑子肯定很乱,有时间的话还是需要自己动手调试一下。本文只是串一下整体思路,所以功能性的源码没有一律分析。

其实了解这些才是最重要的。

客户发送请求至前台控制器DispatcherServletDispatcherServlet收到请求调用HandlerMapping解决器映射器。解决器映射器根据请求url找到具体的解决器,生成解决器对象及解决器阻拦器(假如有则生成)一并返回给DispatcherServlet。DispatcherServlet通过HandlerAdapter解决器适配器调用解决器HandlerAdapter执行解决器(handler,也叫后台控制器)。Controller执行完成返回ModelAndViewHandlerAdapter将handler执行结果ModelAndView返回给DispatcherServletDispatcherServlet将ModelAndView传给ViewReslover视图解析器ViewReslover解析后返回具体View对象DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。DispatcherServlet响应客户读者分享

在这给大家推荐一个微信公众号,那里每天都会有技术干货、技术动向、职业生涯、行业热点、职场趣事等一切有关于程序员的内容分享。更有海量Java架构、移动互联网架构相关源码视频,面试资料,电子书籍截止于4月28日免费发放。我看了觉得资源还不错,假如你们有需要的话,扫描下方二维码关注wx公众号免费获取↓↓↓

资源大本营↓↓↓

Java架构资料Java源码解析,到各种框架学习,再到项目实战,一应俱全,包括但不限于:Spring、Mybatis等源码、Java进阶、Java架构师、虚拟机、性能优化、并发编程、数据结构和算法。

Java架构视频资料Java架构视频资料java架构面试专题资料

移动互联网架构资料Android进阶、Android架构、APP开发、NDK板块开发、小程序开发、微信开发。

Android架构资料



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3